﻿using Microsoft.AspNetCore.Components;
using System.Net.Http.Json;

namespace FastapiBlazorBlog.Pages
{

    public class IndexBase : ComponentBase
    {
        [Inject]
        public HttpClient Http { get; set; }

        [Parameter]
        [SupplyParameterFromQuery(Name = "page")]
        public int? Page { get; set; } = 1;

        [Parameter]
        [SupplyParameterFromQuery(Name = "perPage")]
        public int? PerPage { get; set; } = 6;


        public string searchTxt = "";

        public class RespData<T>
        {
            public int Code { get; set; }
            public string Msg { get; set; }
            public List<T> Data { get; set; } = new List<T>();
        }

        public class Category
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
        public class CategoryDto
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        public class ArticleDto
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public string Description { get; set; }
            public string Content { get; set; }
            public int Created_at { get; set; }
            public int Updated_at { get; set; }
            public Category Category { get; set; }
        }

        public List<CategoryDto> categories = new List<CategoryDto>();
        public List<ArticleDto> articles = new List<ArticleDto>();


        /// <summary>
        /// 文章搜索
        /// </summary>
        /// <returns></returns>
        public async Task SearchArticle()
        {
            Console.WriteLine("searchTxt: " + searchTxt);
            var artRes = await Http.GetFromJsonAsync<RespData<ArticleDto>>($"/api/article/search/{searchTxt}");
            if (artRes != null && artRes.Data != null)
            {
                articles = artRes.Data;
            }
        }

        protected override async Task OnInitializedAsync()
        {
            var cateRes = await Http.GetFromJsonAsync<RespData<CategoryDto>>("/api/categories");
            categories = cateRes.Data;

            var artRes = await Http.GetFromJsonAsync<RespData<ArticleDto>>("/api/articles");
            if (artRes != null && artRes.Data != null)
            {
                articles = artRes.Data;
            }
            await base.OnInitializedAsync();
        }
    }
}
